package it.gtd.swimpool.controller.resources;

import it.gtd.swimpool.model.entity.Administrator;
import it.gtd.swimpool.model.entity.SuperUser;
import it.gtd.swimpool.model.entity.User;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import static com.google.common.base.Preconditions.checkState;

public abstract class SecuredResource {
    @PersistenceContext
    private EntityManager entityManager;

    protected User checkUser(String sessionId) {
        if (sessionId == null) throw new IllegalAccessError("User not logged in!");

        String decodedId = null;
        try {
            decodedId = URLDecoder.decode(sessionId, "UTF-8");
            User user = entityManager.createNamedQuery("User.bySessionId", User.class).
                setParameter("session_id", decodedId).getSingleResult();

            if (!user.isActive()) throw new IllegalAccessError("User is not active!");

            return user;
        } catch (NoResultException _) {
            throw new IllegalAccessError("No session with id " + decodedId);
        } catch (UnsupportedEncodingException e) {
            checkState(false, e.getCause());
            return null;
        }
    }

    protected Administrator checkAdministrator(String sessionId) {
        User user = checkUser(sessionId);

        if (Administrator.class.isInstance(user)) {
            return (Administrator) user;
        } else {
            throw new IllegalAccessError("User is not an administrator");
        }
    }

    protected SuperUser checkSuperUser(String sessionId) {
        User user = checkUser(sessionId);

        if (SuperUser.class.isInstance(user)) {
            return (SuperUser) user;
        } else {
            throw new IllegalAccessError("User is not an administrator");
        }
    }

    protected static String escape(String input) {
        return input.replace("<", "&lt;")
                    .replace(">", "&gt;")
                    .replace("&", "&amp;");
    }
}
